package cn.yunhe.service.serviceImpl;

import cn.yunhe.dao.UserDao;
import cn.yunhe.entity.UserInfo;
import cn.yunhe.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findUserByUserName(s);
        // 存放角色
        ArrayList<SimpleGrantedAuthority> arrayList = new ArrayList<>();
        List<cn.yunhe.entity.Role> roles = userInfo.getRoles();
        for (cn.yunhe.entity.Role role : roles) {
            arrayList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        boolean flag = userInfo.getStatus() == 1 ? true : false;
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), flag, true, true, true, arrayList);
        return user;
    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public void insertUser(UserInfo userInfo) {
        userDao.insertUser(userInfo);
    }

    @Override
    public void deleteUser(Integer userId) {
        userDao.deleteUserById(userId);
        userDao.deleteUrByUserId(userId);

    }

    @Override
    public UserInfo findUserByIdAndAllRole(Integer id) {

        return userDao.findUserByIdAndAllRole(id);
    }

    @Override
    public UserInfo findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<UserInfo> findUserByLike(String userName) {
        return userDao.selectUserByLike(userName);
    }

}
